package com.unionpay.upyzt.resp;

import com.google.gson.*;
import com.unionpay.upyzt.net.UpyztResponse;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

@Data
@Accessors(chain = true)
public abstract class UpyztResp implements UpyztRespInterface, Serializable {

    /**
     * 请求 Id
     */
    private String requestId;

    public static final Gson PRETTY_PRINT_GSON = new GsonBuilder()
            .setPrettyPrinting()
            .serializeNulls()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .disableHtmlEscaping()
            .registerTypeAdapter(LocalDate.class,
                    (JsonSerializer<LocalDate>) (localDateTime, type, jsonSerializationContext) ->
                            new JsonPrimitive(localDateTime.format(DateTimeFormatter.ISO_DATE)))
            .registerTypeAdapter(LocalDateTime.class,
                    (JsonSerializer<LocalDateTime>) (localDateTime, type, jsonSerializationContext) ->
                            new JsonPrimitive(localDateTime.format(DateTimeFormatter.ISO_DATE_TIME)))
            .registerTypeAdapter(OffsetDateTime.class,
                    (JsonSerializer<OffsetDateTime>) (offsetDateTime, type, jsonSerializationContext) ->
                            new JsonPrimitive(offsetDateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)))
            .create();

    public static Gson getPrettyPrintGson() {
        return PRETTY_PRINT_GSON;
    }

    @Override
    public String toString() {
        return getPrettyPrintGson().toJson(this);
    }

    private transient UpyztResponse lastResponse;
}
